package cn.itcast.service.impl;

import cn.itcast.anno.LogOperation;
import cn.itcast.exception.DeleteNonEmptyException;
import cn.itcast.mapper.DeptMapper;
import cn.itcast.mapper.EmpMapper;
import cn.itcast.pojo.Dept;
import cn.itcast.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;

    @Override
    @LogOperation
    public List<Dept> list() {
        List<Dept> deptList = deptMapper.findAll();
        return deptList;
    }

    @Override
    public void deleteById(Integer id) {
        //判断是否有员工
        Integer count = empMapper.countByDeptID(id);
        if (count>0){
            throw new DeleteNonEmptyException("部门人数不为0，不能删除");
        }else {
            /*这里一定，一定要写else，否则，抛出异常后继续向下执行*/
            deptMapper.deleteById(id);
        }

    }

    @Override
    public void save(Dept dept) {
        //填充基础数据
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());

        deptMapper.insert(dept);

    }

    @Override
    public Dept getById(Integer id) {
        Dept dept = deptMapper.getById(id);
        return dept;
    }

    @Override
    public void updateById(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.updateById(dept);
    }
}
